import os
from openai import OpenAI
import requests
import base64
import time
import json
import sys

os.environ["http_proxy"] = "http://127.0.0.1:10808"
os.environ["https_proxy"] = "http://127.0.0.1:10808"

access_token = "24.9825cfb6262e262a5caa6fef4f531037.2592000.1713240501.282335-56894520"
api_key = "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"
# photoURL = "E:\\study\\AIstudy\\api\\target\\classes\\static\\photo\\shijuan.jpg"


def ocr(photo_url, baidu_access_token):
    """
    调用百度云接口,完成对照片的ocr
    :param photo_url: 图片的路径
    :param baidu_access_token: 百度云的access_token
    :return: ocr的识别结果 json
    """
    # request_url = "https://aip.baidubce.com/rest/2.0/ocr/v1/doc_analysis"
    request_url = "https://aip.baidubce.com/rest/2.0/ocr/v1/accurate"
    # 二进制方式打开图片文件
    f = open(photo_url, "rb")
    img = base64.b64encode(f.read())
    params = {"image": img, "language_type": "CHN_ENG", "result_type": "big"}
    request_url = request_url + "?access_token=" + baidu_access_token
    headers = {"content-type": "application/x-www-form-urlencoded"}
    response = requests.post(request_url, data=params, headers=headers)
    if response:
        # print(response.json())
        # print("获取response成功")
        return response.json()


def call_openai(api_key, prompt):
    """
    封装调用openai的接口
    :param api_key: openai_key
    :param prompt: 输入给gpt的提示词语
    :return: str open_ai的返回结果
    """
    client = OpenAI(
        api_key=api_key,
    )
    response = client.chat.completions.create(
        model="gpt-3.5-turbo", messages=[{"role": "user", "content": prompt}]
    )
    return response.choices[0].message.content.strip()


# 使用数学统计的方法修改格式的
def identifying_test_questions(
    photo_url, question_type, baidu_access_token, openai_key
):
    """
    完成对纸卷照片的ocr和返回原文，以及对应的选项
    :param photo_url: str 照片的路径
    :param question_type: str 问题类型 包括阅读(reading)，作文(writing)，翻译(translation)
    :param baidu_access_token: 百度云ocr的key
    :param openai_key: openai的key
    :return: 一个json格式，里面包含原文和各小题及其对应的选项
    """
    # 调用ocr 提取对应的信息
    ocr_res = ocr(photo_url, baidu_access_token)
    # 使用这个json生成对应的promt
    # 先计算出最大宽度 带位置的，高精度的ocr
    max_width = 0
    for words in ocr_res["words_result"]:
        max_width = max(max_width, words["location"]["width"])

    article = " "
    # 在最大的50行里面的，后面只加空格，其他的都加换行符
    for words in ocr_res["words_result"]:
        if words["location"]["width"] >= max_width - 50:
            # 后面只加空格
            article = article + words["words"] + " "
        else:
            article = article + words["words"] + "\n" + "  "

    # print("====================修改格式后的阅读===========================")
    # print(article)

    # 利用正确的格式返回我们需要的json格式
    final_prompt = (
        """
    Please generate a JSON object from the given English reading comprehension question, which includes the original text ,question and the options. The JSON should have separate fields for the original text and each option. Here's the reading comprehension question:\n\n[Insert the reading comprehension question here, including the original text and all the options.]\n\nEnsure that the original text is formatted exactly as it is in the input, and each option is separated into its own field within the JSON object. The output should be in a valid JSON format.
    下面是输入和输出的一个格式
    输入：一篇英文阅读，包括原文和选项
    输出：只能以json格式输出,下面这个json就是对应的输出
    {
      "original_text": "This is the original text of the reading comprehension question. It should be formatted exactly as it appears in the input.",
      "questions": [
        {
          "question_number": 1,
          "question": "Why are race walkers conditioned athletes?",
          "options": [  
            {"Option": This is the first option for the reading comprehension question."},  
            {"Option": This is the second option for the reading comprehension question."},  
            ]  
        },
        {
          "question_number": 2,
          "question": "Why are race walkers conditioned athletes?",
          "options": [  
            {"Option": This is the first option for the reading comprehension question."},  
            {"Option": This is the second option for the reading comprehension question."},  
            ]  
        },

      ]
    }
    要求：
    （1）现在根据上面的提示，对下面这篇阅读题进行分割，并且返回对应的json格式。只返回json格式，不能有其他废话。
    （2）在original_text对应的字符串中，必须保持原来输入的阅读段落格式，不能合并成一段话，这个很重要，必须完成！！！也就是必须保证阅读正文对应的换行符位置不能改变！！！
    （2）在original_text对应的字符串中，必须保持原来输入的阅读段落格式，不能合并成一段话，这个很重要，必须完成！！！也就是必须保证阅读正文对应的换行符位置不能改变！！！
    （2）在original_text对应的字符串中，必须保持原来输入的阅读段落格式，不能合并成一段话，这个很重要，必须完成！！！也就是必须保证阅读正文对应的换行符位置不能改变！！！
    英语阅读：
    """
        + f"""{article}"""
    )
    # print("==================最后的prompt==============")
    # print(final_prompt)

    # 利用最后的prompt，调用gpt
    res = call_openai(api_key=api_key, prompt=final_prompt)
    # print("=======================最后的结果======================")
    print(res)
    # return json.loads(res)


if __name__ == "__main__":

    photoURL = sys.argv[1]
    photoURL = os.path.abspath(".") + "/api/target/classes/static/photo/" + photoURL

    res = identifying_test_questions(
        photo_url=photoURL,
        baidu_access_token=access_token,
        openai_key=api_key,
        question_type="",
    )
    # print(res["original_text"])
